package com.gaofei.controller;

import java.io.File;
import java.io.IOException;
import java.util.UUID;

import org.apache.dubbo.config.annotation.Reference;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.gaofei.domain.Brand;
import com.gaofei.service.BrandService;
import com.github.pagehelper.PageInfo;

@Controller
@RequestMapping("brand")
public class BrandController {

	@Reference
	BrandService brandService;
	
	//添加方法
	@RequestMapping("add")
	@ResponseBody
	public boolean add(Brand brand,MultipartFile filePic) {
		if(filePic!=null&&!filePic.isEmpty()) {
			try {
				// 获取原始文件的名称
				String originalFilename = filePic.getOriginalFilename();
				// 获取文件的后缀名
				String subName = originalFilename.substring(originalFilename.lastIndexOf("."));
				// 使用uuid拼接前缀
				String preName = UUID.randomUUID().toString();

				// 获得新的文件名
				String newName = preName + subName;

				// 开始上传

				filePic.transferTo(new File("D:/upload/", newName));
				
				//把上传的路径封装到brand实体类里
				brand.setPicPath(newName);
				
				brandService.add(brand);
				
				return true;
			} catch (Exception e) {
				e.printStackTrace();
				return false;
			} 
		}
		return false;
	}
	
	
	@RequestMapping("toAdd")
	public String toAdd() {
		return "brand/addBrand";
	}
	
	@RequestMapping("list")
	public String list(Model m,@RequestParam(defaultValue="1") int pageNum,@RequestParam(defaultValue="5")int pageSize) {
		
		PageInfo<Brand> info = brandService.findAll(pageNum, pageSize);
		m.addAttribute("info", info);
		return "brand/list";
		
	}
}
